package lewiszlw.sso.server.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import lewiszlw.sso.server.constant.Constants;
import lewiszlw.sso.server.constant.OAuthTokenType;
import lewiszlw.sso.server.entity.AccountEntity;
import lewiszlw.sso.server.entity.PartnerEntity;
import lewiszlw.sso.server.entity.PartnerProductEntity;
import lewiszlw.sso.server.entity.ShipmentEntity;
import lewiszlw.sso.server.mapper.AccountMapper;
import lewiszlw.sso.server.mapper.PartnerMapper;
import lewiszlw.sso.server.mapper.PartnerProductMapper;
import lewiszlw.sso.server.mapper.ShipmentMapper;
import lewiszlw.sso.server.model.ValidationResult;
import lewiszlw.sso.server.util.CommonUtil;
import lewiszlw.sso.server.util.SnowflakeIdUtil;
import lewiszlw.sso.server.util.WebUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * Desc:
 *
 * @author zhanglinwei02
 * @date 2019-06-06
 */
@Service
public class SsoService {

    @Autowired
    private OAuthSerivce oAuthSerivce;
    @Autowired
    private ShipmentMapper shipmentMapper;
    @Autowired
    private PartnerProductMapper productMapper;
    @Autowired
    private PartnerMapper partnerMapper;
    @Autowired
    private AccountMapper accountMapper;

    /**
     * 判断是否登录
     * true：已登录，false：未登录
     */
    public ValidationResult validateLogin(HttpServletRequest request) {
        Cookie cookie = WebUtils.getCookie(request, Constants.SSO_LOGIN_ACCESS_TOKEN_COOKIE_NAME);
        // 验证cookie
        if (cookie != null) {
            String accessToken = cookie.getValue();
            return oAuthSerivce.validateToken(accessToken, OAuthTokenType.ACCESS_TOKEN);
        }
        // cookie为空则验证header中是否携带access token
        String accessToken = request.getHeader(Constants.SSO_LOGIN_ACCESS_TOKEN_COOKIE_NAME);
        if (!StringUtils.isEmpty(accessToken)) {
            return oAuthSerivce.validateToken(accessToken, OAuthTokenType.ACCESS_TOKEN);
        }
        return ValidationResult.createFailValidationResult("未登录");
    }

    public Map<String,Object> headPartner(int shipId,int productId) throws IOException {
        Map<String, Object> map = new HashMap<>();
        CommonUtil commonUtil = new CommonUtil();
        List<String> params = new ArrayList<>();
        String token = "7s2h3843hjj290726khsnn782ns0s76ss";
        String timestamp = String.valueOf(System.currentTimeMillis());
        String eventId = String.valueOf(System.currentTimeMillis());
        params.add(eventId);
        params.add(timestamp);
        params.add(token);
        Collections.sort(params);
        String localSignature = StringUtils.join(params, "");
        String signature = commonUtil.sha256(localSignature);
        String shipmentUrl = "http://api.nanofintax.com/channel/api/partner?signature=" + signature + "&timestamp=" + timestamp + "&eventId=" + eventId;
        ShipmentEntity shipmentEntity = shipmentMapper.queryShipmentById(shipId);
        PartnerProductEntity partnerProductEntity = productMapper.queryPartnerProductById(productId);
        shipmentEntity.setPartnerProductInfo(partnerProductEntity);
        JSONObject json = (JSONObject) JSONObject.toJSON(shipmentEntity);
        System.out.println("有度税智发货接口发送数据:" + json);
        String body = send(shipmentUrl, json, "UTF-8");
        System.out.println("有度税智发货接口返回数据:" + body);
        Map<String, Object> returnMap = (Map<String, Object>) JSONObject.parse(body);
        String code = (String) returnMap.get("code");
        String message = (String) returnMap.get("message");
        if (StringUtils.equals(code, "0")) {
            JSONObject resultMap = (JSONObject) returnMap.get("result");
            String signId = (String) resultMap.get("signId");
            PartnerEntity partnerEntity = partnerMapper.queryPartnerByOpenId(shipmentEntity.getOpenId());
            partnerEntity.setInstanceId(signId);
            partnerMapper.update(partnerEntity);
            JSONObject appInfoMap = (JSONObject) resultMap.get("appInfo");
            String authUrl = (String) appInfoMap.get("authUrl");
            map.put("authUrl", authUrl);
            map.put("openId", shipmentEntity.getOpenId());
        }
        map.put("code", code);
        map.put("message", message);
        return map;
    }

    public Map<String,Object> headOpenPartner(int partnerId) throws IOException {
        Map<String, Object> map = new HashMap<>();
        String body = "";

        CommonUtil commonUtil = new CommonUtil();
        List<String> params = new ArrayList<>();
        String token = "7s2h3843hjj290726khsnn782ns0s76ss";
        String timestamp = String.valueOf(System.currentTimeMillis());
        String eventId = String.valueOf(System.currentTimeMillis());
        params.add(eventId);
        params.add(timestamp);
        params.add(token);
        Collections.sort(params);
        String localSignature = StringUtils.join(params, "");
        String signature = commonUtil.sha256(localSignature);
        String shipmentUrl = "http://api.nanofintax.com/channel/api/partner/open?signature=" + signature + "&timestamp=" + timestamp + "&eventId=" + eventId;
        PartnerEntity partnerEntity = partnerMapper.queryPartnerById(partnerId);
        JSONObject json = (JSONObject) JSONObject.toJSON(partnerEntity);
        System.out.println("传输json数据:" + json);
        body = send(shipmentUrl, json, "UTF-8");
        System.out.println("有度税智开通租户接口返回数据:" + body);
        Map<String, Object> returnMap = (Map<String, Object>) JSONObject.parse(body);
        String code = (String) returnMap.get("code");
        String message = (String) returnMap.get("message");
        if (StringUtils.equals(code, "0")) {
            JSONObject resultMap = (JSONObject) returnMap.get("result");
            String accessKey = (String) resultMap.get("accessKey");
            String accessSecret = (String) resultMap.get("accessSecret");
            String encodingAesKey = (String) resultMap.get("encodingAesKey");
            String appId = (String) resultMap.get("appId");
            String tenantId = (String) resultMap.get("tenantId");
            String customerId = (String) resultMap.get("customerId");
            String companyId = (String) resultMap.get("companyId");
            AccountEntity accountEntity = accountMapper.queryById(Integer.valueOf(partnerEntity.getOpenId()));
            accountEntity.setAccessKey(accessKey);
            accountEntity.setAccessSecret(accessSecret);
            accountEntity.setEncodingAesKey(encodingAesKey);
            accountEntity.setAppId(appId);
            accountEntity.setTenantId(tenantId);
            accountEntity.setCustomerId(customerId);
            accountEntity.setCompanyId(companyId);
            accountMapper.update(accountEntity);
        }
        map.put("code", code);
        map.put("message", message);
        return map;
    }

    /**
     * 发送post请求
     * @param url  路径
     * @param jsonObject  参数(json类型)
     * @param encoding 编码格式
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String send(String url, JSONObject jsonObject, String encoding) throws ParseException, IOException {
        String body = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);
        //装填参数
        StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
        s.setContentEncoding(new BasicHeader("utf-8","application/json"));
        //设置参数到请求对象中
        httpPost.setEntity(s);
        System.out.println("请求地址："+url);
        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        //httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;
    }

    public List<AccountEntity> queryAccountList(){
        List<AccountEntity> accountEntities = accountMapper.queryAccountList();
        return accountEntities;
    }


}
